package com.coldworks.coldjoke.activity;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnCancelListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import com.coldworks.base.BaseActivity;
import com.coldworks.base.manager.BaseNetworkManager;
import com.coldworks.base.util.BaseCONST;
import com.coldworks.coldjoke.R;
import com.coldworks.coldjoke.manager.UserManager;
import com.coldworks.coldjoke.util.NetworkUtil;
import com.coldworks.coldjoke.util.RegularUtil;
import com.coldworks.coldjoke.util.UrlUtil;

public class RegisterActivity extends BaseActivity {

	private ImageButton backBtn;
	private Button loginBtn;
	private Button registerBtn;
	private EditText emailEditText;
	private EditText userNameEditText;
	private EditText pwdEditText;
	private ProgressDialog progressDialog;

	private RegisterTask registerTask = null;

	private String email;
	private String userName;
	private String pwd;
	private List<NameValuePair> params;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		try {
			setContentView(R.layout.activity_register);
			setUpView();
			setUpListener();
		} catch (Exception e) {
			log.error("", e);
		}
	}

	private void setUpView() {
		registerBtn = (Button) findViewById(R.id.button_register);
		loginBtn = (Button) findViewById(R.id.button_login);
		backBtn = (ImageButton) findViewById(R.id.button_back);
		emailEditText = (EditText) findViewById(R.id.input_email);
		pwdEditText = (EditText) findViewById(R.id.input_pwd);
		userNameEditText = (EditText) findViewById(R.id.input_name);
	}

	private void setUpListener() {

		registerBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				registerNow();
			}
		});

		loginBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				startActivity(new Intent(RegisterActivity.this,
						LoginActivity.class));
				overridePendingTransition(android.R.anim.fade_in,
						android.R.anim.fade_out);
				finish();
			}
		});

		backBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});
	}

	private void registerNow() {
		if (!RegularUtil.checkEmailAdress(emailEditText.getText().toString())) {
			Toast.makeText(context, R.string.register_no_email,
					Toast.LENGTH_LONG).show();
		} else if (!RegularUtil.checkPwd(pwdEditText.getText().toString())) {
			pwdEditText.getText().clear();
			Toast.makeText(context, R.string.register_no_pwd, Toast.LENGTH_LONG)
					.show();
		} else if (!RegularUtil.checkUserName(userNameEditText.getText()
				.toString())) {
			Toast.makeText(context, R.string.register_no_name,
					Toast.LENGTH_LONG).show();
		} else {
			email = emailEditText.getText().toString();
			// emailEditText.getText().clear();
			pwd = pwdEditText.getText().toString();
			// pwdEditText.getText().clear();
			userName = userNameEditText.getText().toString();
			// 开始进行注册
			registerTask = new RegisterTask();
			registerTask.execute();
		}
	}

	private class RegisterTask extends AsyncTask<Void, Integer, Integer> {

		private String msg = null;

		public RegisterTask() {
			// 初始化Post数据
			params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("username", userName));
			params.add(new BasicNameValuePair("email", email));
			params.add(new BasicNameValuePair("password", pwd));
			params.add(new BasicNameValuePair("sex", "保密"));
		}

		@Override
		protected void onPreExecute() {
			progressDialog = new ProgressDialog(context);
			progressDialog.setMessage(context.getResources().getString(
					R.string.register_ing));
			progressDialog.setIndeterminate(true);
			progressDialog.setCancelable(true);
			progressDialog.setOnCancelListener(new OnCancelListener() {

				@Override
				public void onCancel(DialogInterface dialog) {
					registerTask.cancel(true);
					registerTask = null;
				}
			});
			progressDialog.show();

		}

		@Override
		protected Integer doInBackground(Void... param) {
			HttpPost httpPost = new HttpPost(UrlUtil.getRegisterUrl());
			try {
				httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
				HttpResponse response = BaseNetworkManager.getInstance()
						.createHttpClient(context).execute(httpPost);
				if (isCancelled()) {
					log.info("cancelled");
					return BaseCONST.OP.CANCEL;
				}

				if (response.getStatusLine().getStatusCode() == 200) {
					Header contentEncoding = response
							.getFirstHeader("Content-Encoding");
					JSONObject jsonObject = null;
					if (contentEncoding != null
							&& contentEncoding.getValue().equalsIgnoreCase(
									"gzip")) {
						jsonObject = NetworkUtil.getInstance()
								.getJsonObjectByGzip(
										response.getEntity().getContent());
					} else {
						jsonObject = NetworkUtil.getInstance().getJSONObject(
								response.getEntity().getContent());
					}
					if (jsonObject == null) {
						log.info("error-->jsonObject==null");
						return BaseCONST.OP.ERR_NET;
					}
					if (jsonObject.getString("success").equals("true")) {
						log.info("succ");
						return BaseCONST.OP.SUCC;
					} else { // 将注册不成功的原因返回去
						log.info("failed");
						msg = jsonObject.getString("error_info");
						return BaseCONST.OP.FAIL;
					}
				} else {
					log.info("error net-->staus code=="
							+ response.getStatusLine().getStatusCode());
					return BaseCONST.OP.ERR_NET;
				}
			} catch (ClientProtocolException e) {
				log.error("", e);
				return BaseCONST.OP.ERR_NET;
			} catch (UnsupportedEncodingException e) {
				log.error("", e);
				return BaseCONST.OP.ERR_NET;
			} catch (IOException e) {
				log.error("", e);
				return BaseCONST.OP.ERR_NET;
			} catch (JSONException e) {
				log.error("", e);
				return BaseCONST.OP.ERR_NET;
			}
		}

		@Override
		protected void onPostExecute(Integer result) {
			if (progressDialog != null) {
				progressDialog.dismiss();
			}
			switch (result) {
			case BaseCONST.OP.SUCC:
				Toast.makeText(context, R.string.register_success,
						Toast.LENGTH_SHORT).show();
				UserManager.getInstance().setUserEmail(email);
				UserManager.getInstance().setUserName(userName);
				startActivity(new Intent(RegisterActivity.this,
						LoginActivity.class));
				finish();
				break;
			case BaseCONST.OP.ERR_NET:
				Toast.makeText(context, R.string.err_connecting,
						Toast.LENGTH_LONG).show();
				log.info("error net");
				break;
			case BaseCONST.OP.FAIL:
				log.info("failed");
				pwdEditText.getText().clear();
				Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
				break;
			case BaseCONST.OP.CANCEL:
				break;
			default:
				break;
			}
			registerTask = null;
		}

	}

}
